//
//  NetworkTools.m
//  weibo
//
//  Created by qiuming on 15/12/21.
//  Copyright © 2015年 qiuming. All rights reserved.
//

#import "NetworkTools.h"
/// 服务器地址
NSString *const BASE_URL = @"https://api.weibo.com/";
/// appKey
NSString *const APP_KEY = @"3861352594";
/// appSecret
NSString *const APP_SECRET = @"62d746654e95645736a923c082acf0ce";
/// 回调地址
NSString *const REDIRECT_URL = @"http://www.baidu.com";

@protocol NetworkToolsProxy <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;
@end

@interface NetworkTools()<NetworkToolsProxy>


@end


@implementation NetworkTools

+ (instancetype)sharedNetwordTool {
    static NetworkTools *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // 1.设置请求超时时长
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        config.timeoutIntervalForRequest = 20;
        instance = [[self alloc]initWithBaseURL:[NSURL URLWithString:BASE_URL] sessionConfiguration:config];
        // 2.数据解析
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
        
        [(AFJSONResponseSerializer *)instance.responseSerializer setRemovesKeysWithNullValues:YES];
    });
    return instance;
}

- (void)requestMethod:(RequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(void(^)(id resuld, NSError *error))finished {
    
    NSString *methodName = (method == GET) ? @"GET" : @"POST";
    
    [[self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        // 成功时回调
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        // 失败时回调
        finished(nil, error);
    }] resume];
    
}

// MARK: - 获取授权码
/// - see: [http://open.weibo.com/wiki/Oauth2/authorize]
- (NSURL *)oauthUrl {
    NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", APP_KEY, REDIRECT_URL];
    return [NSURL URLWithString:urlString];
}

/// MARK: - 由授权码获取Token
/// - see: [http://open.weibo.com/wiki/OAuth2/access_token]
- (void)accessTokenWithCode:(NSString *)code finish:(requestCallBack)finish {
    
    NSString *urlString = @"oauth2/access_token";
    
    NSDictionary *parameters = @{@"client_id": APP_KEY,
                                 @"client_secret": APP_SECRET,
                                 @"grant_type": @"authorization_code",
                                 @"code": code,
                                 @"redirect_uri": REDIRECT_URL};
    
    // 发送网络请求获取Token
    [self requestMethod:POST URLString:urlString parameters:parameters finished:finish];
    
}

/// 加载用户信息
/// @see - http://open.weibo.com/wiki/2/users/show
- (void)loadUserWithUid:(NSString *)uid accessToken:(NSString *)token finish:(requestCallBack)finish {
    
    NSString *urlString = @"2/users/show.json";
    
    NSDictionary *parameters = @{@"access_token": token, @"uid": uid};
    
    [self requestMethod:GET URLString:urlString parameters:parameters finished:finish];
}

/// 加载微博数据
/// @see [http://open.weibo.com/wiki/2/statuses/friends_timeline]
- (void)loadStutasWithToken:(NSString *)token finish:(requestCallBack)finish {
    
    NSString *urlString = @"2/statuses/friends_timeline.json";
    NSDictionary *parameters = @{@"access_token": token};
    [self requestMethod:GET URLString:urlString parameters:parameters finished:finish];
}

@end
















